package com.lancea12.buster.android;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import javax.net.ServerSocketFactory;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class RobotServerRunnable implements Runnable {

	private static final int port = 1221;
	private ServerSocket serverSock;
	private boolean controllerConnected = false;
    private Handler textHandler;
    private Handler responseHandler;
    private RobotMessageHandler arduinoHandler;
    
    
	
	public RobotServerRunnable(Handler textHandler, RobotMessageHandler arduinoHandler) {
		this.textHandler = textHandler;
		this.arduinoHandler = arduinoHandler;
		try {
			serverSock = ServerSocketFactory.getDefault().createServerSocket(port);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
    	responseHandler = new Handler(){
    		public void handleMessage(Message msg) {
				if(msg.getData().getString("socket").equals("disconnected")){
					controllerConnected = false;
				}
				Message newMsg = new Message();
				newMsg.copyFrom(msg);
			//	RobotServerRunnable.this.mHandler.sendMessage(newMsg);
    		};
    	};
		
	}
	
	@Override
	public void run() {
		while(true){
			try {
				Socket endpoint = serverSock.accept();
				Log.d("Buster", "trying to accept");
				new Thread(new RobotEndpoint(endpoint, textHandler, responseHandler, arduinoHandler, !controllerConnected)).start();
				if(!controllerConnected){
					controllerConnected = true;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
